import FlagImage from '@/components/FlagImage';
import * as c from '@/services/consts';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
import {
  CheckCircleFilled,
  CloseCircleFilled,
  UserOutlined,
} from '@ant-design/icons';
import { CheckCard, PageContainer, ProCard } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, {
  ActionType,
  ColumnsState,
  ProColumns,
} from '@ant-design/pro-table';
import { Badge,  Card, Space, Tag,  } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import LineChart from '@/components/LineChart';
import dayjs from 'dayjs';
import Countdown from 'antd/es/statistic/Countdown';

const dateFormat = 'MM-DD HH:mm:ss';//YYYY-
let urlGrafanaServer = "http://50.7.214.138:9090/api/v1/query_range?query=" //"https://prometheus.biubiuvpn.app:2053/api/v1/query_range?query=";//
// let ist =Math.round(utils.dateAdd(new Date(), 'd', -1).getTime() / 1000);
// let iet =  Math.round(Date.now() / 1000);


const getAllInstIds = (group: API.VpnGroupMonitorModel) => {
  if (group) {
    let ids = '';
    for (let item of group?.data) {
      if (ids != '') ids = ids + '|';
      ids = `${ids}${item.ip}:9100`;
    }
    return ids;
  }
  return '';
};  



export const ChartCard: React.FC<{
  ids: string;
  unit: string;
  interval: number;
  controlState: number;
}> = (props) => {
  const{ids, unit, interval, controlState } = props;

  let ist = Math.round(utils.dateAdd(new Date(), unit, -interval).getTime() / 1000);
  let iet =  Math.round(Date.now() / 1000);
  let istep = Math.round((iet - ist) / 100);//180
  istep = istep < 60 ? 60 : istep;

  // console.log(group);

  const [chartData, setChartData] = useState<API.ChartDataItem[] | undefined>(undefined);
  // const [onlineData, setOnlineData] = useState<API.UserStatChartItem[] | undefined>(undefined);

  //sum(irate(node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'104.194.11.79:9100|158.51.121.97:9100'}[90s])*8)
  let recvUrl = `${urlGrafanaServer}sum(irate(node_network_receive_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${ids}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  let transUrl = `${urlGrafanaServer}sum(irate(node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${ids}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  
  const loadCharts = async()=>{
    let datas : API.ChartDataItem[] = [];
    // console.log(recvUrl);
    var result = await api.getGroupTrafficData(recvUrl);
    // console.log(result);
    if (result && result.status == 'success') {
      let len = result.data ? 
                  result.data.result ? 
                    result.data.result.length > 0 ? 
                      result.data.result[0].values ? result.data.result[0].values?.length : 0
                    : 0 : 0 :0;
      for(let i=0; i<len; i++){
        let d = result.data.result[0].values[i];
        datas.push({
          title: '接收(Mb)',
          date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
          count: utils.formatRateMb(d[1] * 1, true)
        });
      }
    }

    // console.log(transUrl);
    result = await api.getGroupTrafficData(transUrl);
    // console.log(result);
    if (result && result.status == 'success') {
      let len = result.data ? 
                  result.data.result ? 
                    result.data.result.length > 0 ? 
                      result.data.result[0].values ? result.data.result[0].values?.length : 0
                    : 0 : 0 :0;
      for(let i=0; i<len; i++){
        let d = result.data.result[0].values[i];
        datas.push({
          title: '发送(Mb)',
          date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
          count: utils.formatRateMb(d[1] * 1, true)
        });
      }
    }

    setChartData(datas);
  }

  // const loadOnline = async () => {
  //   const result = await api.groupOnlinelist(
  //     {
  //       code: group?.code,
  //       // productId: productId == c.DefaultOptionAll.key ? '' : productId,
  //     },
  //     undefined,undefined,
  //   );
  //   if (result && result.success) {
  //     setOnlineData(result.data);
  //   }
  //   else{
  //     setOnlineData(undefined);
  //   }
  // };

  // const { getSupplier,} = useModel('useGlobalModel', (model) => ({
  //   getSupplier: model.getSupplier,
  // }));

  // const getSupplierText = () => {
  //   let texts : string[] = [];
  //   if(group.data){
  //     for(let d of group.data){
  //       let t = getSupplier(d.supplierId);
  //       if(t && !texts.includes(t.name)){
  //         texts.push(t.name);
  //       }
  //     }
  //   }
  //   let t = texts.join(',');
  //   if(t.length > 0){
  //     return <Tag color='blue'>{t}</Tag>
  //   }
  //   return '';
  // }

  
  useEffect(() => {
    loadCharts();
    // loadOnline();
  }, [controlState]);

  const renderChartTag = useMemo(() => {
      return (
        <>
          <div>
          <LineChart
            data={chartData ?? []}
            xfield="date"
            yfield="count"
            seriesField="title"
            height={200}
            lineWidth={1}
            displayLabel={undefined}
            displayPoint={false}
            backColor={undefined}//#E6F3FF
          />
          </div> 
        </>
      );
  }, [chartData]);

  // const renderOnlineTag = useMemo(() => {
  //     return (
  //       <>
  //         <div>
  //         <LineChart
  //           data={onlineData ?? []}
  //           xfield="date"
  //           yfield="count"
  //           seriesField="title"
  //           height={150}
  //           displayLabel={{}}
  //           displayPoint={true}
  //           backColor={undefined}
  //         />
  //         </div> 
  //       </>
  //     );
  // }, [onlineData]);

  return <>
  <div>{renderChartTag}</div>
  {/* <div>{renderOnlineTag}</div> */}
  </>;
};







const VpnGroupTreeList: React.FC = (props: any) => {
  const [monitorServers, setMonitorServers] = useState<API.VpnServer[] | undefined>(undefined);
  const [monitorGroups, setMonitorGroups] = useState<API.VpnGroupModel[] | undefined>(undefined);
  const [monitorSuppliers, setMonitorSuppliers] = useState<API.ServerSupplierModel[] | undefined>(undefined);
  const [countdownTicks, setCountdownTicks] = useState<number>(-1);
  const [controlState, setControlState] = useState<number>(0);

  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [monitorOptions, setMonitorOptions] = useState<any[]>([]);
  const [monitorData, setMonitorData] = useState<any | undefined>(undefined);  

  
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [vipUserCount, setVipUserCount] = useState<number>(0);
  const [elseUserCount, setElseUserCount] = useState<number>(0);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  


  const { getProductMenuItems, getVpnGroupList
  } = useModel('useGlobalModel', (model) => ({
    getProductMenuItems: model.getProductMenuItems,
    getVpnGroupList: model.getVpnGroupList,
  }));

  const productMenuItems = getProductMenuItems(true);


  const loadBaseData = async () => {
    const result = await api.trafficMonitorBaseData();
    if (result && result.success) {
      setMonitorServers(result.servers);
      setMonitorGroups(result.groups);
      setMonitorSuppliers(result.suppliers);
    } else {
      setMonitorServers(undefined);
      setMonitorGroups(undefined);
      setMonitorSuppliers(undefined);
    }
    setCountdownTicks(Date.now() + 60000);
    setDataLoading(false);
  };

  useEffect(() => {
    loadBaseData();
  }, [ ]);
  
  // useEffect(() => {
  //   getGroupStats();
  // }, [monitorServers, monitorGroups, monitorGroups ]);

  // const getChartDatas = async(ids: string, unit: string, interval: number) => {
  //   let ist = Math.round(utils.dateAdd(new Date(), unit, -interval).getTime() / 1000);
  //   let iet =  Math.round(Date.now() / 1000);
  //   let istep = Math.round((iet - ist) / 100);//180
  //   istep = istep < 60 ? 60 : istep;

  //   let recvUrl = `${urlGrafanaServer}sum(irate(node_network_receive_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${ids}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  //   let transUrl = `${urlGrafanaServer}sum(irate(node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*|cni.*|ifb.*',instance=~'${ids}'}[90s])*8)&start=${ist}&end=${iet}&step=${istep}`;
  
  //   let datas : API.ChartDataItem[] = [];
  //   let resultRecv = await api.getGroupTrafficData(recvUrl);
  //   let resultTrans = await api.getGroupTrafficData(transUrl);
  //   // console.log(result);
  //   if (resultRecv && resultRecv.status == 'success') {
  //     let len = resultRecv.data ? 
  //     resultRecv.data.result ? 
  //     resultRecv.data.result.length > 0 ? 
  //     resultRecv.data.result[0].values ? 
  //     resultRecv.data.result[0].values?.length : 0 : 0 : 0 :0;
  //     for(let i=0; i<len; i++){
  //       let d = resultRecv.data.result[0].values[i];
  //       datas.push({
  //         title: '接收(Mb)',
  //         date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
  //         count: utils.formatRateMb(d[1] * 1, true)
  //       });
  //     }
  //   }

  //   if (resultTrans && resultTrans.status == 'success') {
  //     let len = resultTrans.data ? 
  //     resultTrans.data.result ? 
  //     resultTrans.data.result.length > 0 ? 
  //     resultTrans.data.result[0].values ? resultTrans.data.result[0].values?.length : 0 : 0 : 0 :0;
  //     for(let i=0; i<len; i++){
  //       let d = resultTrans.data.result[0].values[i];
  //       datas.push({
  //         title: '发送(Mb)',
  //         date: dayjs(new Date(d[0] * 1000)).format(dateFormat),
  //         count: utils.formatRateMb(d[1] * 1, true)
  //       });
  //     }
  //   }

  //   return datas;
  // }
  
  // const getStep = (unit: string, interval: number) => {
  //   let ist = Math.round(utils.dateAdd(new Date(), unit, -interval).getTime() / 1000);
  //   let iet =  Math.round(Date.now() / 1000);
  //   let istep = Math.round((iet - ist) / 100);//180
  //   istep = istep < 60 ? 60 : istep;
  //   return istep;
  // };  
  

  // const getGroupStats = async () => {
  //   if(!monitorGroups) return undefined;

  //   let dataSource = [];
  //   for(let ch of monitorGroups){
  //     let chartData = await getChartDatas(getIdsByGroup(ch), 'h', 12);
  //     dataSource.push({
  //       title: <><div>
  //         <div style={{color:"#777"}}>{`${ch.fullName} [${ch.code}]` }</div>
  //         </div></>,
  //       value: ch.id,
  //       //style: { width: 220, minHeight: 60, overflow: 'auto', padding:0 }, old:width:168
  //       size:'large',
  //       description: <><Space>
  //       <div>
  //       <LineChart
  //         data={chartData ?? []}
  //         xfield="date"
  //         yfield="count"
  //         seriesField="title"
  //         height={150}
  //         displayLabel={undefined}
  //         displayPoint={false}
  //         backColor={undefined}//#E6F3FF
  //       />
  //       </div> 
  //           </Space>
  //           </>
  //     });          
  //   }

  //   setMonitorData( dataSource);
  // };

  const reload = () => {
    if (countdownTicks > 0) {
      setControlState(new Date().getTime());
      setCountdownTicks(Date.now() + 60000);
    }
    // loadBaseData();
  };

  const getIdsByGroup = (group: API.VpnGroupModel) => {
    if (group) {
      let ids = '';
      for (let item of monitorServers) {
        if(item.groupIds.includes(group.id))
        if (ids != '') ids = ids + '|';
        ids = `${ids}${item.ip}:9100`;
      }
      return ids;
    }

    return '';
  };  



  

  return (
    <PageContainer>

      <ProCard gutter={0} extra={<>
            <Space>
              <Countdown
                title=""
                key="cdRefresh"
                value={countdownTicks}
                format="s"
                prefix=""
                suffix="秒"
                valueStyle={{
                  fontSize: 14,
                  color: 'gray',
                }}
                // style={{ visibility: countdownVisible }}
                onFinish={reload}
              />
            </Space>
      </>}>
        <CheckCard.Group key="searchGrop">
          {monitorGroups?.map((val) => {
            return <CheckCard
            title={<>
              <div>
              {val.status ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}
              &nbsp;{c.getMemberLevelText(val.memberLevel)}
              &nbsp;<FlagImage flagName={val.flag} />{val.name} [{val.code}]
              </div>
            </>}
            value={val.id}
            style={{width:600}}
            description={
              <ChartCard ids={getIdsByGroup(val)} unit='h' interval={12} controlState={controlState} />
            }
          />
          })}
        </CheckCard.Group>
      </ProCard>

    </PageContainer>
  );
};

export default VpnGroupTreeList;
